package com.peanut.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.nacos.api.utils.StringUtils;
import com.peanut.common.Result;
import com.peanut.em.ResultEnum;
import com.peanut.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class TokenFilter implements GlobalFilter , Ordered {
    //需要实现的过滤方法
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request对象
        ServerHttpRequest request = exchange.getRequest();
        //通过request对象获取请求头数据
        String token = request.getHeaders().getFirst("AuthToken");
        //检查token是否存在
        if (StringUtils.isBlank(token)) {
            return denyAccess(exchange);
        }
        try{
            Claims claims = new JwtUtil().parseJwt(token);
            claims.getSubject();
        }catch (Exception e){
            e.printStackTrace();
            return denyAccess(exchange);
        }
        //token不为null并且正确
        return chain.filter(exchange);
    }

    //封住统一返回值
    private Mono<Void> denyAccess(ServerWebExchange exchange) {
        //获取response对象
        ServerHttpResponse response = exchange.getResponse();
        //设置响应状态
        response.setStatusCode(HttpStatus.OK);
        //设置返回头编码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        byte[] bytes = JSONObject.toJSONBytes(Result.R(ResultEnum.NO_LOGIN), SerializerFeature.WriteMapNullValue);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        Result.R(ResultEnum.NO_LOGIN);
        return response.writeWith(Mono.just(buffer));
    }

    //表示过滤器执行的顺序,数值越小越先执行
    @Override
    public int getOrder() {
        return 0;
    }
}
